package slap.util;

import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * MimeTypes utils
 */
public class MimeTypes {
	
	protected static final Logger logger = LoggerFactory.getLogger(MimeTypes.class);
	
    private static Properties mimetypes = null;

    public static String getMimeType(String filename) {
        return getMimeType(filename, "");
    }

    public static String getMimeType(String ext, String defaultMimeType) {
        String mimeType = mimetypes().getProperty(ext);
        if (mimeType == null) {
            return defaultMimeType;
        }
        return mimeType;
    }
    
    public static String getContentType(String ext){
    	return getContentType(ext, "application/octet-stream");
    }
    
    public static String getContentType(String ext, String defaultContentType){
    	String contentType = getMimeType(ext, null);
    	if (contentType == null){
    		contentType =  defaultContentType;
    	}
    	
    	if (contentType != null && contentType.startsWith("text/")){
    		return contentType + "; charset=utf-8";
    	}
    	return contentType;
    }
    
    public static boolean isValidMimeType(String mimeType) {
        if (mimeType == null) {
            return false;
        } else if (mimeType.indexOf(";") != -1) {
            return mimetypes().contains(mimeType.split(";")[0]);
        } else {
            return mimetypes().contains(mimeType);
        }
    }

    private static Properties mimetypes() {
        if (mimetypes == null) {
            try {
                InputStream is = MimeTypes.class.getClassLoader().getResourceAsStream("slap/util/mime-types.properties");
                mimetypes = new Properties();
                mimetypes.load(is);
            } catch (Exception ex) {
                logger.warn("Could not load specific types.properties file.");
            }
        }
        return mimetypes;
    }

}
